<?php
// +----------------------------------------------------------------------
// | xiongrui [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.xiongrui.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.xiongrui.cn>
// +----------------------------------------------------------------------

namespace app\index\controller;
use app\common\controller\Fornt;
use app\common\model\Order as OrderModel;
use app\common\model\Cart as CartModel;
use app\common\model\AddressNew;
use app\common\model\Goods;
use app\common\model\Goodsrule;
use app\common\model\Goodscat;
use app\common\model\DeliveryArayacak;
use app\common\model\CouponList;
use app\common\model\WxUser;
use app\common\model\Comment;
use think\Request;
//use Com\Lib\Auth;
use Com;
// import("Com.Lib.WxPayException");
// import("Com.Lib.WxPayConfig");
// import("Com.Lib.WxPayDataBase");
//use org\Auth;
// require_once "../lib/WxPay.Api.php";WxPayDataBase
// require_once "WxPay.JsApiPay.php";
// require_once "WxPay.Config.php";
// require_once 'log.php';
// use mail;//此步骤相当于引入了所有命名空间为mail的文件

// $mail=new \mail\PHPMailer();//PHPMailer is a name of class;


/**
 * 订单页面
 */
class Order extends Fornt{

	public function index($orderid=null){

		$mapss['user_id'] = USER_ID;
		$mapss['buystatus'] = array('gt','-1');
		$mapss['company_id'] = array('eq', 0);
    $list = OrderModel::where($mapss)->order('id desc')->select();

		//取消5小时没有支付的订单
		$map                = array('user_id' => USER_ID,'pay'=>1,'buystatus'=>0);
		$map['create_time'] = array('lt', time()-5*3600);
		OrderModel::where($map)->update(['buystatus'=>-1]);

		//发送短信




		if($orderid){
			$info = OrderModel::get($orderid);
     	$num  = $info->OrderShoplist()->sum('num');
			if(!$num){
				$num = 1;
			}
			sendTemplateMessage($info['title'], $num);
		}

    $this->assign('list', $list);
		update_session(USER_ID);
    return $this->fetch();
	}

	
	public function wxpaytest($id = null){
	     
// 	    //可以成功支付的  微信jdk
// 	    $userInfo = WxUser::where('id', USER_ID)->find();
	
	    	
// 	        $openid = $userInfo['openid'];
// 	    $body = "testxgw";
// 	    $out_trade_no = rand(10000,100000000);//订单号单号
// 	    $total_fee = 12;//价格
// 	    $notify_url = 'http://www.xgw0851.com/index/pay/notify2';
// 	    $pay = & load_wechat('Pay');
// 	    //获得预付款id
// 	    $prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
// 	    $options = $pay->createMchPay($prepayid);
// 	    $options = json_encode($options);
	    
	    
// 	    $this->assign('body', $body);
// 	    $this->assign('openid', $openid);
// 	    $this->assign('options', $options);
// 	    $this->assign('trade_no', $out_trade_no);
// 	    $this->assign('title', '付款');
	
	    
	 
// 	 $this->assign('openid', "123");
	        //跳转微信支付页面
	       return $this->fetch();
	
	     
	}
	
	
  public function detail($id = null){
		//订单信息
		$orderInfo = OrderModel::get($id);
		$this->assign('orderInfo', $orderInfo);
    return $this->fetch();
  }
	public function placedetail($id = null){
		//产地订单信息
		$orderInfo = OrderModel::get($id);
		$this->assign('orderInfo', $orderInfo);
    return $this->fetch();
  }

	public function add(){
		$cartInfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);
		$addressMap = [
			'user_id'=>USER_ID,
			'type'=>0,
			'defaults'=>1
		];
		//'type'=> cookie('address_type') ? cookie('address_type') : 0,



		$addressInfo = AddressNew::where($addressMap)->find();
		//判断邮寄地址运费
		// if(cookie('shopindex')=='index/index/mailindex'){
		// 	$addressInfo['freight'] = 0;
		// }

		$goodsInfo = Goods::all($cartInfo['good_id_arr']);
		$userInfo = session('user');
		if($userInfo['balance'] < 0){
			$this->error('账号存在异常，请联系客户');
		}
		//$this->judge_addresstype($addressInfo['first_area'], $addressInfo['type']);

		if(is_array($cartInfo['rule_id_arr'])){
			//验证库存
			// foreach ($cartInfo['rule_id_arr'] as $num => $value) {
			// 	$stock =  Goodsrule::where('id', $value)->value('stock');
			// 	if($stock < $num){
			// 		$this->error('商品库存不足');
			// 	}
			// }
		}else{
			$this->error('购物车为空');
		}

		//验证地址
		if(!$addressInfo){
			$this->error('还没有添加地址！');
		}

		//判断是否是会员, 是会员打折
		//$cartInfo['price'] = parent::isMemberAndDiscount($cartInfo['price']);

		//判断是否只有活动商品【如果只有活动商品，取消运费补贴】
		$eventsGoods = parent::isEventsGoods($cartInfo['goods_feature']);
		//判断团购商品
		if(input('is_tg') == 1){
			$eventsGoods = 1;
		}

		if(cookie('goodsmodel_id') == 3){
			//包邮模型
			$addressInfo['freight'] = 0;
		}




		//运费补贴
		$subsidy = 0;
		if(cookie('way') == 1){
			$subsidy = getSubsidy($cartInfo['price'], $addressInfo['freight']);
		}






		$data['subsidy']  =  $subsidy; //运费补贴
		$data['user_id'] = USER_ID;
    $data['address_id']  = $addressInfo->id;
		$data['cover_id']  = $goodsInfo[0]['cover_id'];
		$data['user_name']  = $addressInfo->name;
		$data['nick_name']  = $userInfo['nickname'];
		$data['tel']  = $addressInfo->tel;
		$data['address']  = $addressInfo->address_full.''. $addressInfo->address.''.$addressInfo->house_number;
		$data['way']  = cookie('way') ? cookie('way') : 1;
		$data['pay']  = cookie('pay');
		$data['rebate_code']  = WxUser::where('id', USER_ID)->value('rebate_code');
		$data['deliverytime']  = cookie('deliverytime') ? cookie('deliverytime') : '';
		$data['shop_price']  = $cartInfo['price'];
		$data['freight']  = $addressInfo['freight'];
		$data['balance']  =  $userInfo['balance'];
		$data['title']  = $goodsInfo[0]['good_name'];
		$data['out_trade_no']  =  USER_ID.date("YmdHis");
		$data['remark']  =  input('remark');
		$data['place_id']  =  $addressInfo->place_id;
		$data['disparity']  =  $addressInfo->disparity;
		$data['index_type'] = input('index_type') ? input('index_type') : 0;
		$data['pack_price']  =  $cartInfo['pack_price'];
		$data['group_time']  =  input('group_time') ? input('group_time') : 0;
		$data['goodsmodel_id']  =  cookie('goodsmodel_id');



		//自提地点
		if($data['way'] == 2){
				$data['zt_address']  = DeliveryArayacak::where(['id'=>cookie('zt_address')])->value('name');
				$data['freight']  = 0;
		}
		if($data['pay'] == 2){
				$data['buystatus']  = 1; //货到付款，待发货
		}



		//优惠券
		$data['coupon_price'] = 0;
		if(cookie('?couponlist_id')){
			$couponlist = CouponList::where('id', cookie('couponlist_id'))->find();
			if($cartInfo['price'] < $couponlist['total']){
				$this->error('购物车商品未消费满'.$couponlist['total']);
			}else{
				$data['coupon_id'] = $couponlist['id'];
				$data['coupon_price'] = $couponlist['price'];
			}
		}

		//邮寄 运费为15元
		if($data['way'] == 3){
			$data['freight'] = 15;
		}
		//全场满600减 运费为0
		if($data['shop_price'] > 600){
			$data['freight'] = 0;
		}

		$data['total']  = $data['shop_price']+$data['freight']+$cartInfo['pack_price']-$subsidy;
		$data['pay_price'] = $data['total']-$data['balance']-$data['coupon_price'];
		//第二天折扣
		$payZk = config('nextday_discount');
		if($payZk < 1 &&  $payZk > 0){
			$data['pay_price'] = $data['pay_price']*$payZk;
			$data['pay_zk'] = $payZk;
		}

		//全余额支付
		if($data['pay_price']<=0){
			$data['pay_price'] = 0;
			$data['pay'] = 3;
			$data['buystatus']  = 1;
			$data['balance']  =  $data['total']; //使用的余额总数就是 支付的价格
		}



		$result = OrderModel::create($data);


		//保存订单商品
		$shopListData = array();
		foreach ($cartInfo['list'] as $key => $value) {
			$shopListData[$key]['good_id'] = $value->good_id;
			$shopListData[$key]['user_id'] = USER_ID;
			$shopListData[$key]['rule_id'] = $value->rule_id;
			$shopListData[$key]['rule_name'] = $value->rule_name;
			$shopListData[$key]['num'] = $value->num;
			$shopListData[$key]['good_name'] = $value->good_name;
			$shopListData[$key]['price'] = $value->good_price;
			$shopListData[$key]['index_type'] = $data['index_type'];
			$shopListData[$key]['group_time'] = $data['group_time'];
		}

    $result->OrderShoplist()->saveAll($shopListData);

		if($result){
			//清空购物车
			CartModel::destroy(['user_id'=>USER_ID]);
			//余额支付和微信支付减余额
			if($data['pay'] == 3){
				WxUser::where('id', USER_ID)->setDec('balance', $data['total']);
			}elseif($data['pay'] == 1){
				WxUser::where('id', USER_ID)->update(['balance' => 0]);
			}

			//更新优惠券状态和使用时间
			if(cookie('?couponlist_id')){
				CouponList::where('id', cookie('couponlist_id'))->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
			}
			//减库存
			foreach ($cartInfo['rule_id_arr'] as $num => $value) {
				 Goodsrule::where('id', $value)->setDec('stock', $num);
			}
			update_session(USER_ID);



		}







   


		if($data['pay'] == 2 || $data['pay'] == 3){
			sendTemplateMessage($data['title'], $cartInfo['num']);
			//  sendSms($result['nick_name'], $result['create_time'], $result['out_trade_no'], '15885108322');
			//  sendSms($result['nick_name'], $result['create_time'], $result['out_trade_no'], '13638516023');
			//发送给客户经理
				$rebateinfo = db('member')->where('uid',$data['rebate_code'])->find();
				if($rebateinfo['mobile']){
					sendSms2($result['nick_name'], $result['create_time'],  substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$rebateinfo['username'], $rebateinfo['mobile']);
				}
				$reusername = $rebateinfo['username'] ? $rebateinfo['username'] : '未设置';
				// sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, '15885108322');
				// sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, '13638516023');

				if($result['index_type'] == 1){
					$sendSmsPhones = explode(',',config('sendsms_m2'));
				}else{
					$sendSmsPhones = explode(',',config('sendsms_m1'));
				}
				foreach ($sendSmsPhones as $value) {
					sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, (string)$value);
				}

			//调整购买成功页面
			return $this->fetch('success');
		}
		
		$openid = $userInfo['openid'];
		$body = $result['title'];
		$out_trade_no = $result['out_trade_no'];
		$total_fee = $result['pay_price']*100;
		$notify_url = 'http://www.xgw0851.com/index/pay/notify';
		$pay = & load_wechat('Pay');
		$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
		$options = $pay->createMchPay($prepayid);
		$options = json_encode($options);

		$this->assign('options', $options);
		$this->assign('info', $result);
		
		//跳转微信支付页面wxpaytest wxpaynew
		return $this->fetch('wxpaynew');

	}

	public function pay($id = null){
		if($id){
			$userInfo = session('user');
			$result = OrderModel::get($id);
			$openid = $userInfo['openid'];
			$body = $result['title'];
			$out_trade_no = $result['out_trade_no'];
			$total_fee = $result['pay_price']*100;
			$notify_url = 'http://www.xgw0851.com/index/pay/notify';
			$pay = & load_wechat('Pay');
			$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
			$options = $pay->createMchPay($prepayid);
			$options = json_encode($options);

			$this->assign('options', $options);
			$this->assign('info', $result);

			//跳转微信支付页面
			return $this->fetch('wxpaynew');
		}
	}
	
	
	

	
// 	public function wxpaytest($id = null){
	    

// 	   // $tools = A('Com/JsApiPay');  
// 	    //$openId = \Com\JsApiPay::GetOpenid();
	    
// //           $this->assign('openId', "aabbdd");
	    
// //           $this->assign('test', "test123");
// // 	    //跳转微信支付页面
// // 	       return $this->fetch();
	    
	    
// // 	    //②、统一下单
// // 	    $input = new WxPayUnifiedOrder();
// // 	    $input->SetBody("test");
// // 	    $input->SetAttach("test");
// // 	    $input->SetOut_trade_no("sdkphp".date("YmdHis"));
// // 	    $input->SetTotal_fee("1");
// // 	    $input->SetTime_start(date("YmdHis"));
// // 	    $input->SetTime_expire(date("YmdHis", time() + 600));
// // 	    $input->SetGoods_tag("test");
// // 	    $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
// // 	    $input->SetTrade_type("JSAPI");
// // 	    $input->SetOpenid($openId);
// // 	    $config = new WxPayConfig();
// // 	    $order = WxPayApi::unifiedOrder($config, $input);
// // 	    echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
// // 	    printf_info($order);
// // 	    $jsApiParameters = $tools->GetJsApiParameters($order);
	    
// // 	    $userInfo = WxUser::where('id', USER_ID)->find();
	    
// // 	    $result['title'] = '线下支付'.date("YmdHis");
// // 	    $result['total'] = input('post.total');
// // 	    $result['offlinepay_status'] = input('post.offlinepay_status');
// // 	    $coupon_id = input('post.coupon_id');
// // 	    $result['shop_price']  = $result['total'];
	    
	    
// // 	    $result['user_name']  = $userInfo['nickname'];
// // 	    $result['nick_name']  = $userInfo['nickname'];
// // 	    $result['pay'] = 4;
// // 	    $result['user_id'] = USER_ID;
// // 	    $result['buystatus']  = 0;
// // 	    $result['out_trade_no']  =  USER_ID.date("YmdHis");
// // 	    $result['rebate_code']  = WxUser::where('id', USER_ID)->value('rebate_code');
	    
// // 	    //优惠券
// // 	    $result['coupon_price'] = 0;
// // 	    if($coupon_id){
// // 	        $couponlist = CouponList::where('id', $coupon_id)->find();
// // 	        if($result['total'] < $couponlist['total']){
// // 	            $this->error('付款金额未消费满'.$couponlist['total']);
// // 	        }else{
// // 	            $result['coupon_id'] = $couponlist['id'];
// // 	            $result['coupon_price'] = $couponlist['price'];
	    
// // 	        }
// // 	    }
	    
// // 	    $result['pay_price']  = $result['total']-$result['coupon_price'];
	    
	    
// // 	    $result = OrderModel::create($result);
	    
	    
// // 	    if($coupon_id){
// // 	        CouponList::where('id', $coupon_id)->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
// // 	    }
	    
// // 	    //使用余额支付
	    
// // 	    if($userInfo['balance'] >0 && $userInfo['balance'] >= $result['pay_price']){
// // 	        $chazhi = $userInfo['balance'] - $result['pay_price'];
// // 	        $jf = $userInfo['integral'] +  $result['pay_price'];
// // 	        db('WxUser')->where('id', USER_ID)->setDec('balance', $result['pay_price']);
// // 	        db('WxUser')->where('id', USER_ID)->setInc('integral', $result['pay_price']);
// // 	        OrderModel::where('id', $result->id)->update(['balance'=>$result['pay_price'], 'buystatus' => 4]);  //使用余额支付,并修改状态
// // 	        //发送给用户
// // 	        if(!empty($userInfo['phone'])){
// // 	            sendcomSms('SMS_67655286', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'balance'=>(string)$chazhi, 'integral'=>(string)$jf], (string)$userInfo['phone']);
// // 	        }
// // 	        //发送给管理元
// // 	        sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '15885108322');
// // 	        sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '13638516023');
	    
	    
// // 	        return $this->fetch('success');
// // 	    }elseif($userInfo['balance'] >0 && $userInfo['balance'] < $result['pay_price']){
// // 	        OrderModel::where('id', $result->id)->update(['balance'=>$userInfo['balance']]);  //使用余额支付
// // 	        db('WxUser')->where('id', USER_ID)->setDec('balance', $userInfo['balance']);
// // 	        $result['pay_price'] =  $result['pay_price'] - $userInfo['balance'];
// // 	    }
// // 	    OrderModel::where('id', $result->id)->update(['pay_price'=>$result['pay_price']]);
	    
	    
// // 	    // 	    //②、统一下单
// // 	    // 	    $input = new WxPayUnifiedOrder();
// // 	    // 	    $input->SetBody("test");
// // 	    // 	    $input->SetAttach("test");
// // 	    // 	    $input->SetOut_trade_no("sdkphp".date("YmdHis"));
// // 	    // 	    $input->SetTotal_fee("1");
// // 	    // 	    $input->SetTime_start(date("YmdHis"));
// // 	    // 	    $input->SetTime_expire(date("YmdHis", time() + 600));
// // 	    // 	    $input->SetGoods_tag("test");
// // 	    // 	    $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
// // 	    // 	    $input->SetTrade_type("JSAPI");
// // 	    // 	    $input->SetOpenid($openId);
// // 	    // 	    $config = new WxPayConfig();
// // 	    // 	    $order = WxPayApi::unifiedOrder($config, $input);
// // 	    // 	    echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
// // 	    // 	    printf_info($order);
// // 	    // 	    $jsApiParameters = $tools->GetJsApiParameters($order);
// 	    //	    $options["sub_mch_id"]='1513820611';
	    
// // 	    $tools = new JsApiPay();
// // 	    $openId = $tools->GetOpenid();
	    
// // 	    //②、统一下单
// // 	    $input = new WxPayUnifiedOrder();
// // 	    $input->SetBody("test");
// // 	    $input->SetAttach("test");
// // 	    $input->SetOut_trade_no("sdkphp".date("YmdHis"));
// // 	    $input->SetTotal_fee("1");
// // 	    $input->SetTime_start(date("YmdHis"));
// // 	    $input->SetTime_expire(date("YmdHis", time() + 600));
// // 	    $input->SetGoods_tag("test");
// // 	    $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
// // 	    $input->SetTrade_type("JSAPI");
// // 	    $input->SetOpenid($openId);
// // 	    $config = new WxPayConfig();
// // 	    $order = WxPayApi::unifiedOrder($config, $input);
// // 	    echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
// // 	    printf_info($order);
// // 	    $jsApiParameters = $tools->GetJsApiParameters($order);
	    
// // 	    $userInfo = WxUser::where('id', USER_ID)->find();
// // 	    //$openid = $userInfo['openid'];

	    
	    
// // 	    //可以成功支付的  微信jdk
// // 	    $openid='or59quDHDyO0WnuMkrzICBrsdJOM';
// // 	    $body = "testxgw";
// // 	    $out_trade_no = rand(10000,100000000);//订单号单号
// // 	    $total_fee = 12;//价格
// // 	    $notify_url = 'http://www.xgw0851.com/index/pay/notify2';
// // 	    $pay = & load_wechat('Pay');
// // 	    //获得预付款id
// // 	    $prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
// // 	    $options = $pay->createMchPay($prepayid);
// // 	    $options = json_encode($options);
	    
	    
// // 	    $this->assign('body', $body);
// // 	    $this->assign('openid', $openid);
// // 	    $this->assign('options', $options);
// // 	    $this->assign('trade_no', $out_trade_no);
// // 	    $this->assign('title', '付款');
	
	    
// 	// $a = new JsApiPay();
// 	  //  $a = new JsApiPay();
// 	    $a = new Auth();
// 	     //$b =new WxPay();
// 	      $b =new Lib\WxPayNotify();
//        // $a->xx();
	 
// 	 $this->assign('openid', "123");
// 	        //跳转微信支付页面
// 	       return $this->fetch();
	    
// 	}
	
	
// 	/**
// 	 * 线下付款
// 	 * @return [type] [description]
// 	 */
// 	public function offlinepaytest($total='', $coupon_id=null){
// 	    if(IS_POST){
// 	        if(empty($total)){
// 	            $this->error('正在返回上一页');
// 	        }
	
// 	        $userInfo = WxUser::where('id', USER_ID)->find();
	
// 	        $result['title'] = '线下支付'.date("YmdHis");
// 	        $result['total'] = input('post.total');
// 	        $result['offlinepay_status'] = input('post.offlinepay_status');//线下状态
// 	        // $coupon_id = input('post.coupon_id');
// 	        $result['shop_price']  = $result['total'];
	
	
// 	        $result['user_name']  = $userInfo['nickname'];
// 	        $result['nick_name']  = $userInfo['nickname'];
// 	        $result['pay'] = 4;
// 	        $result['user_id'] = USER_ID;
// 	        $result['buystatus']  = 0;
// 	        $result['out_trade_no']  =  USER_ID.date("YmdHis");
// 	        //折扣
// 	        // $result['rebate_code']  = WxUser::where('id', USER_ID)->value('rebate_code');
	
// 	        //优惠券
// 	        // $result['coupon_price'] = 0;
// 	        //优惠卷
// 	        // 	        if($coupon_id){
// 	        // 	            $couponlist = CouponList::where('id', $coupon_id)->find();
// 	        // 	            if($result['total'] < $couponlist['total']){
// 	        // 	                $this->error('付款金额未消费满'.$couponlist['total']);
// 	        // 	            }else{
// 	        // 	                $result['coupon_id'] = $couponlist['id'];
// 	        // 	                $result['coupon_price'] = $couponlist['price'];
	
// 	        // 	            }
// 	        // 	        }
	
// 	        // $result['pay_price']  = $result['total']-$result['coupon_price'];
// 	        //支付金额
// 	        $result['pay_price']  = $result['total'];
	         
// 	        //使用红包卷
	         
// 	        if ($userInfo['useredsum'] >0 && $result['pay_price'] >= 30){
// 	            $result['pay_price']=$result['pay_price']-10;
// 	        }
	         
	         
// 	        $result = OrderModel::create($result);
	
// 	        //优惠卷
// 	        // 	        if($coupon_id){
// 	        // 	            CouponList::where('id', $coupon_id)->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
// 	        // 	        }
	
// 	        //使用余额支付
	
// 	        // 	        if($userInfo['balance'] >0 && $userInfo['balance'] >= $result['pay_price']){
// 	        // 	            $chazhi = $userInfo['balance'] - $result['pay_price'];
// 	        // 	            $jf = $userInfo['integral'] +  $result['pay_price'];
// 	        // 	            db('WxUser')->where('id', USER_ID)->setDec('balance', $result['pay_price']);
// 	        // 	            db('WxUser')->where('id', USER_ID)->setInc('integral', $result['pay_price']);
// 	        // 	            OrderModel::where('id', $result->id)->update(['balance'=>$result['pay_price'], 'buystatus' => 4]);  //使用余额支付,并修改状态
// 	        // 	            //发送给用户
// 	        // 	            if(!empty($userInfo['phone'])){
// 	        // 	                sendcomSms('SMS_67655286', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'balance'=>(string)$chazhi, 'integral'=>(string)$jf], (string)$userInfo['phone']);
// 	        // 	            }
// 	        // 	            //发送给管理元
// 	        // 	            sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '15885108322');
// 	        // 	            sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '13638516023');
	
	
// 	        // 	            return $this->fetch('success');
// 	        // 	        }elseif($userInfo['balance'] >0 && $userInfo['balance'] < $result['pay_price']){
// 	        // 	            OrderModel::where('id', $result->id)->update(['balance'=>$userInfo['balance']]);  //使用余额支付
// 	        // 	            db('WxUser')->where('id', USER_ID)->setDec('balance', $userInfo['balance']);
// 	        // 	            $result['pay_price'] =  $result['pay_price'] - $userInfo['balance'];
// 	        // 	        }
// 	        // 	        OrderModel::where('id', $result->id)->update(['pay_price'=>$result['pay_price']]);
	
// 	        $openid = $userInfo['openid'];
// 	        $body = $result['out_trade_no'];
// 	        $out_trade_no = $result['out_trade_no'];
// 	        $total_fee = $result['pay_price']*100;
// 	        $notify_url = 'http://www.xgw0851.com/index/pay/notify2';
// 	        $pay = & load_wechat('Pay');
// 	        //获得预付款id
// 	        $prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
// 	        $options = $pay->createMchPay($prepayid);
// 	        $options = json_encode($options);
	
// 	        $this->assign('options', $options);
// 	        $this->assign('info', $result);
// 	        $this->assign('title', '付款');
// 	        return $this->fetch('wxpaytest');
	
// 	    }else{
// 	        $this->redirect('index/cart/pay');
// 	    }
// 	}
	
	/**
	 * 线下付款
	 * @return [type] [description]
	 */
	public function offlinepaytest($total='', $coupon_id=null){
	    if(IS_POST){
	        if(empty($total)){
	            $this->error('正在返回上一页');
	        }
	
	        $userInfo = WxUser::where('id', USER_ID)->find();
	
	        $result['title'] = '线下支付'.date("YmdHis");
	        $result['total'] = input('post.total');
	        $result['offlinepay_status'] = input('post.offlinepay_status');//线下状态
	        $result['shop_price']  = $result['total'];	
	        $result['user_name']  = $userInfo['nickname'];
	        $result['nick_name']  = $userInfo['nickname'];
	        $result['pay'] = 4;
	        $result['user_id'] = USER_ID;
	        $result['buystatus']  = 0;
	        $result['out_trade_no']  =  USER_ID.date("YmdHis");
	  
	        $result['pay_price']  = $result['total'];	       	        
	        if ($userInfo['useredsum'] >0 && $result['pay_price'] >= 30){
	            $result['pay_price']=$result['pay_price']-10;
	        }
	            
	            
	        $result = OrderModel::create($result);	
	        $openid = $userInfo['openid'];
	        $body = $result['out_trade_no'];
	        $out_trade_no = $result['out_trade_no'];
	        $total_fee = $result['pay_price']*100;
	        $notify_url = 'http://www.xgw0851.com/index/pay/notify2';
	        $pay = & load_wechat('Pay');
	        //获得预付款id
	        $prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
	        $options = $pay->createMchPay($prepayid);
	        $options = json_encode($options);
	
	        
	        $this->assign('openid', $openid);
	        $this->assign('options', $options);
	        $this->assign('info', $result);
	        $this->assign('title', '付款');
	        return $this->fetch('wxpaytest');
	
	    }else{
	        $this->redirect('index/cart/paytest');
	    }
	}
	
	/**
	 * 线下付款
	 * @return [type] [description]
	 */
	public function offlinepay($total='', $coupon_id=null){
		if(IS_POST){
			if(empty($total)){
				$this->error('正在返回上一页');
			}

			$userInfo = WxUser::where('id', USER_ID)->find();

			$result['title'] = '线下支付'.date("YmdHis");
			$result['total'] = input('post.total');
			$result['offlinepay_status'] = input('post.offlinepay_status');
			$coupon_id = input('post.coupon_id');
			$result['shop_price']  = $result['total'];


			$result['user_name']  = $userInfo['nickname'];
			$result['nick_name']  = $userInfo['nickname'];
			$result['pay'] = 4;
			$result['user_id'] = USER_ID;
			$result['buystatus']  = 0;
			$result['out_trade_no']  =  USER_ID.date("YmdHis");
			$result['rebate_code']  = WxUser::where('id', USER_ID)->value('rebate_code');

			//优惠券
			$result['coupon_price'] = 0;
			if($coupon_id){
				$couponlist = CouponList::where('id', $coupon_id)->find();
				if($result['total'] < $couponlist['total']){
					$this->error('付款金额未消费满'.$couponlist['total']);
				}else{
					$result['coupon_id'] = $couponlist['id'];
					$result['coupon_price'] = $couponlist['price'];

				}
			}

				$result['pay_price']  = $result['total']-$result['coupon_price'];


			$result = OrderModel::create($result);


			if($coupon_id){
					CouponList::where('id', $coupon_id)->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
			}

			//使用余额支付

			if($userInfo['balance'] >0 && $userInfo['balance'] >= $result['pay_price']){
				$chazhi = $userInfo['balance'] - $result['pay_price'];
				$jf = $userInfo['integral'] +  $result['pay_price'];
				db('WxUser')->where('id', USER_ID)->setDec('balance', $result['pay_price']);
				db('WxUser')->where('id', USER_ID)->setInc('integral', $result['pay_price']);
				OrderModel::where('id', $result->id)->update(['balance'=>$result['pay_price'], 'buystatus' => 4]);  //使用余额支付,并修改状态
				//发送给用户
				if(!empty($userInfo['phone'])){
					sendcomSms('SMS_67655286', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'balance'=>(string)$chazhi, 'integral'=>(string)$jf], (string)$userInfo['phone']);
				}
				//发送给管理元
				sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '15885108322');
				sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '13638516023');


				return $this->fetch('success');
			}elseif($userInfo['balance'] >0 && $userInfo['balance'] < $result['pay_price']){
				OrderModel::where('id', $result->id)->update(['balance'=>$userInfo['balance']]);  //使用余额支付
				db('WxUser')->where('id', USER_ID)->setDec('balance', $userInfo['balance']);
				$result['pay_price'] =  $result['pay_price'] - $userInfo['balance'];
			}
			OrderModel::where('id', $result->id)->update(['pay_price'=>$result['pay_price']]);

			$openid = $userInfo['openid'];
			$body = $result['out_trade_no'];
			$out_trade_no = $result['out_trade_no'];
			$total_fee = $result['pay_price']*100;
			$notify_url = 'http://www.xgw0851.com/index/pay/notify2';
			$pay = & load_wechat('Pay');
			//获得预付款id
			$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
			$options = $pay->createMchPay($prepayid);
			$options = json_encode($options);

			$this->assign('options', $options);
			$this->assign('info', $result);
			$this->assign('title', '付款');
			return $this->fetch('wxpaynew');

		}else{
			$this->redirect('index/cart/pay');
		}
	}
	/**
	 * 自定义付款
	 * @return [type] [description]
	 */
	public function custompay($total, $coupon_id=null){
		if(IS_POST){
			$userInfo = session('user');

			$result['title'] = input('post.title');
			$result['total'] = input('post.total');
			$result['remark']  =  input('post.title');

			$result['nick_name']  = $userInfo['nickname'];
			$result['pay'] = 5; // 5 自定义付款
			$result['deliverytime']  = cookie('deliverytime');  //配送时间
			$result['user_id'] = USER_ID;
			$result['buystatus']  = 0;
			$result['out_trade_no']  =  USER_ID.date("YmdHis");
			$result['rebate_code']  = WxUser::where('id', USER_ID)->value('rebate_code');
			$result['way']  = 1; 	//送货方式  送货上门

			//默认地址
			$addressMap = [
				'user_id'=>USER_ID,
				'type'=> cookie('address_type') ? cookie('address_type') : 0,
				'defaults'=>1
			];
			$addressInfo = AddressNew::where($addressMap)->find();
			if(!$addressInfo){
				$this->error('必须添加地址');
			}
			$result['address_id']  = $addressInfo->id;
			$result['user_name']  = $addressInfo->name;
			$result['tel']  = $addressInfo->tel;
			$result['address']  = $addressInfo->address_full.''. $addressInfo->address.''.$addressInfo->house_number;

			//优惠券
			$coupon_id = input('post.coupon_id');
			if($coupon_id){
				$couponlist = CouponList::where('id', $coupon_id)->find();
				if($result['total'] < $couponlist['total']){
					$this->error('付款金额未消费满'.$couponlist['total']);
				}else{
					$result['total'] = $result['total']-$couponlist['price'];
					$result['coupon_id'] = $couponlist['id'];
					$result['coupon_price'] = $couponlist['price'];

				}
			}

			$result = OrderModel::create($result);


			if($coupon_id){
					CouponList::where('id', $coupon_id)->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
			}

			//使用余额支付

			if($userInfo['balance'] >0 && $userInfo['balance'] >= $result['total']){
				$chazhi = $userInfo['balance'] - $result['total'];
				WxUser::where('id', USER_ID)->update(['balance'=>$chazhi]);  //修改用户余额
				OrderModel::where('id', $result->id)->update(['balance'=>$result['total'], 'buystatus' => 1]);  //使用余额支付,并修改状态
				//发送给用户
				if(!empty($userInfo['phone'])){
					sendcomSms('SMS_67655286', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'balance'=>(string)$chazhi, 'integral'=>(string)$userInfo['integral']], (string)$userInfo['phone']);
				}
				//发送给管理元
				sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '15885108322');
				sendcomSms('SMS_68145090', ['user'=>$userInfo['nickname'], 'time'=>$result['create_time'], 'money'=>(string)$result['total'], 'order'=>substr($result['out_trade_no'],-4)], '13638516023');


				return $this->fetch('success');
			}elseif($userInfo['balance'] >0 && $userInfo['balance'] < $result['total']){
				OrderModel::where('id', $result->id)->update(['balance'=>$userInfo['balance']]);  //使用余额支付
				$result['total'] =  $result['total'] - $userInfo['balance'];
			}


			$openid = $userInfo['openid'];
			$body = $result['out_trade_no'];
			$out_trade_no = $result['out_trade_no'];
			$total_fee = $result['total']*100;
			$notify_url = 'http://www.xgw0851.com/index/pay/notify3';
			$pay = & load_wechat('Pay');
			$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
			$options = $pay->createMchPay($prepayid);
			$options = json_encode($options);

			$this->assign('options', $options);
			$this->assign('info', $result);
			$this->assign('title', '付款');
			return $this->fetch('wxpaynew');

		}else{
			$this->error('参数错误！');
		}
	}

	public function comment($id = null){
	    if (IS_POST) {
				$data = input('post.');
				$data['user_id'] = USER_ID;
				$result = Comment::create($data);
				if($result){
					OrderModel::where('id', $result['order_id'])->update(['is_comment' => 1]);
					action_log('review', 'Comment', USER_ID, USER_ID);
					$this->success('评论成功');
				}
			}else{
				$info = OrderModel::get($id);
				$this->assign('info', $info);
				return $this->fetch();
			}
	}

	/**
	 * 添加订单【产地直发】
	 * @return [type] [description]
	 */
	public function addplacepinkage(){
		//获取购物车信息
		$cartInfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);
		//获取默认地址
		$addressMap = [
			'user_id'=>USER_ID,
			'type'=> cookie('address_type') ? cookie('address_type') : 0,
			'defaults'=>1
		];
		$addressInfo = AddressNew::where($addressMap)->find();
		//验证地址
		if(!$addressInfo){
			$this->error('还没有添加地址！');
		}
		//产地直发运费为0
		$addressInfo['freight'] = 0;
		//获取购物车中商品信息
		$goodsInfo = Goods::all($cartInfo['good_id_arr']);
		//获取用户信息
		$userInfo = session('user');

		//循环验证库存
		$this->verifyStock($cartInfo['rule_id_arr']);

		//获取发送短信的电话
		$sendsmsPhones = Goods::where('id','in',$cartInfo['good_id_arr'])->column('sendsms_phone');
		$sendsmsPhones = json_encode(array_unique($sendsmsPhones));



		//数据赋值
		$data['user_id'] = USER_ID;
    $data['address_id']  = $addressInfo->id;
		$data['cover_id']  = $goodsInfo[0]['cover_id'];
		$data['user_name']  = $addressInfo->name;
		$data['nick_name']  = $userInfo['nickname'];
		$data['tel']  = $addressInfo->tel;
		$data['address']  = $addressInfo->address_full.''. $addressInfo->address.''.$addressInfo->house_number;
		$data['way']  = 1; 	//送货方式  送货上门
		$data['pay']  = cookie('pay');
		$data['rebate_code']  = WxUser::where('id', USER_ID)->value('rebate_code');
		$data['deliverytime']  = cookie('deliverytime') ? cookie('deliverytime') : '';
		$data['shop_price']  = $cartInfo['price'];
		$data['freight']  = $addressInfo['freight'];
		//$data['subsidy']  =  getSubsidy($data['shop_price'], $data['freight']);
		$data['balance']  =  $userInfo['balance'];
		$data['total']  = $data['shop_price']+$data['freight']-$data['balance'];
		$data['title']  = $goodsInfo[0]['good_name'];
		$data['out_trade_no']  =  USER_ID.date("YmdHis");
		$data['remark']  =  input('remark');
		$data['place_id']  =  0; //如果为0 产地直发
		$data['disparity']  =  $addressInfo->disparity;
		$data['sendsms_phones']  =  $sendsmsPhones;
		$data['index_type'] = 2;

		//优惠券
		if(cookie('?couponlist_id')){
			$couponlist = CouponList::where('id', cookie('couponlist_id'))->find();
			if($cartInfo['price'] < $couponlist['total']){
				$this->error('购物车商品未消费满'.$couponlist['total']);
			}else{
				$data['coupon_id'] = $couponlist['id'];
				$data['coupon_price'] = $couponlist['price'];
				$data['total'] = $data['total']-$couponlist['price'];
			}
		}

		//全余额支付
		if($data['total']<=0){
			$data['total'] = $data['total']+$data['balance'];
			$data['pay'] = 3;
			$data['buystatus']  = 1;
			$data['balance']  =  $data['total']; //使用的余额总数就是 支付的价格
		}


		$result = OrderModel::create($data);

		//保存订单商品
		$shopListData = array();
		foreach ($cartInfo['list'] as $key => $value) {
			$shopListData[$key]['good_id'] = $value->good_id;
			$shopListData[$key]['user_id'] = USER_ID;
			$shopListData[$key]['rule_id'] = $value->rule_id;
			$shopListData[$key]['rule_name'] = $value->rule_name;
			$shopListData[$key]['num'] = $value->num;
			$shopListData[$key]['good_name'] = $value->good_name;
			$shopListData[$key]['price'] = $value->good_price;
			$shopListData[$key]['shop_name'] = $value->shop_name;
			$shopListData[$key]['cost_price'] = $value->cost_price;
			$shopListData[$key]['agent_price'] = $value->agent_price;
		}

		$result->OrderShoplist()->saveAll($shopListData);

		if($result){
			//清空购物车
			CartModel::destroy(['user_id'=>USER_ID]);
			//余额支付和微信支付减余额
			if($data['pay'] == 3){
				WxUser::where('id', USER_ID)->setDec('balance', $data['total']);
			}elseif($data['pay'] == 1){
				WxUser::where('id', USER_ID)->update(['balance' => 0]);
			}

			//更新优惠券状态和使用时间
			if(cookie('?couponlist_id')){
				CouponList::where('id', cookie('couponlist_id'))->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
			}
			//减库存
			foreach ($cartInfo['rule_id_arr'] as $num => $value) {
				 Goodsrule::where('id', $value)->setDec('stock', $num);
			}
			update_session(USER_ID);



		}

		if($data['pay'] == 2 || $data['pay'] == 3){
				sendTemplateMessage($data['title'], $cartInfo['num']);
				//发送短信给用户
				$rebateinfo = db('member')->where('uid',$data['rebate_code'])->find();
				if($rebateinfo['mobile']){
					sendSms2($result['nick_name'], $result['create_time'],  substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$rebateinfo['username'], $rebateinfo['mobile']);
				}
				//发送短信给管理员
				$reusername = $rebateinfo['username'] ? $rebateinfo['username'] : '未设置';
				// sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, '15885108322');
				// sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, '13638516023');
				//发送短信给管理员  配置文件中的
				$sendSmsPhones = explode(',',config('sendsms_m3'));
				foreach ($sendSmsPhones as $value) {
				 	sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, (string)$value);
				}

				//查询订单发sendsms_phones 送短信
				// $sendsmsPhones = json_decode($result['sendsms_phones'], true);
				// foreach ($sendsmsPhones as $value) {
				// 	sendSms2($result['nick_name'], $result['create_time'], substr($result['out_trade_no'],-4),(string)$result['total'].config('pay')[$data['pay']],$reusername, (string)$value);
				// }


			//调整购买成功页面
			return $this->fetch('success');
		}



		$openid = $userInfo['openid'];
		$body = $result['title'];
		$out_trade_no = $result['out_trade_no'];
		$total_fee = $result['total']*100;
		$notify_url = 'http://www.xgw0851.com/index/pay/notify';
		$pay = & load_wechat('Pay');
		$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
		$options = $pay->createMchPay($prepayid);
		$options = json_encode($options);

		$this->assign('options', $options);
		$this->assign('info', $result);
		return $this->fetch('wxpaynew');

	}

	protected function verifyStock($ruleIds){
		if(is_array($ruleIds)){
			//验证库存
			foreach ($ruleIds as $num => $value) {
				$stock =  Goodsrule::where('id', $value)->value('stock');
				if($stock < $num){
					$this->error('部分商品库存不足');
				}
			}
		}else{
			$this->error('购物车为空');
		}
	}

	public function acceptorder($id){
		$result = OrderModel::get($id);
		$result->buystatus = 4;
		$result->save();
		$total = ceil($result->total);
		db('WxUser')->where('id',$result->user_id)->setInc('integral', $total);
		$this->success('操作成功！');
	}


	public function editOrderInfo($id, $remark){
		$return = OrderModel::where('id', $id)->update(['remark'=>$remark]);
		if($return){
			$this->success('操作成功！');
		}else {
			$this->error('修改失败！');
		}
	}

	public function delorder($id){
		$result = OrderModel::where('id', $id)->update(['buystatus'=>-1]);
		if($result){
			$info =  OrderModel::where('id', $id)->find();
			if(!empty($info['coupon_id'])){
				db('coupon_list')->where('id',$info['coupon_id'])->update(['status'=>0]);
			}
			if($info['balance'] > 0){
				db('wx_user')->where('id',$info['user_id'])->setInc('balance', $info['balance']);
			}

      return $this->success("删除成功！");
    }else{
      return $this->error("删除失败！");
    }



	}

	/**
	 * 企业添加订单
	 * @return [type] [description]
	 */
	public function qiye(){
		if($this->request->isPost()){

				$info = parent::setQiyeCommon();

				$cartInfo = $info['cinfo'];
				$companyInfo = $info['companyInfo'];
				$qiyeUserInfo = $info['qiyeUserInfo']; // 默认地址


				if(!$qiyeUserInfo){
					$this->error('请先添加用户信息');
				}

				//获取购物车中商品信息
				$goodsInfo = Goods::all($cartInfo['good_id_arr']);
				//获取用户信息
				$userInfo = session('user');

				//循环验证库存
				//$this->verifyStock($cartInfo['rule_id_arr']);
				//订单数据
				$data['user_id'] = USER_ID;
				$data['cover_id']  = $goodsInfo[0]['cover_id'];
				$data['user_name']  = $qiyeUserInfo['username'];
				$data['nick_name']  = $userInfo['nickname'];
				$data['tel']  = $qiyeUserInfo['phone'];
				$data['address']  = $companyInfo['adress'];
				$data['pay']  = $companyInfo['is_wxpay'] == 1 ? 1 : 2; 	//支付方式
				$data['way']  = 1; 	//送货方式  送货上门
				$data['deliverytime']  = $companyInfo['delivery_dec'];
				$data['shop_price']  = $cartInfo['price'];
				$data['total']  = $data['shop_price'];
				$data['title']  = $goodsInfo[0]['good_name'];
				$data['out_trade_no']  =  USER_ID.date("YmdHis");
				$data['balance']  =  $userInfo['balance'];
				$data['company_id']  =  $companyInfo['id'];
				$data['buystatus']  = 0;
				if($data['pay'] == 2){
					$data['buystatus']  = 1;
				}


				//优惠券
				$data['coupon_price'] = 0;
				if(cookie('?couponlist_id')){
					$couponlist = CouponList::where('id', cookie('couponlist_id'))->find();
					if($cartInfo['price'] < $couponlist['total']){
						$this->error('购物车商品未消费满'.$couponlist['total']);
					}else{
						$data['coupon_id'] = $couponlist['id'];
						$data['coupon_price'] = $couponlist['price'];
					}
				}


				$data['total']  = $data['shop_price'];
				$data['pay_price'] = $data['total']-$data['balance']-$data['coupon_price'];

				//全余额支付
				if($data['pay_price']<=0){
					$data['pay_price'] = 0;
					$data['pay'] = 3;
					$data['buystatus']  = 1;
					$data['balance']  =  $data['total']; //使用的余额总数就是 支付的价格
				}


				//当日编号
				$dayNo = OrderModel::where(['company_id'=>$companyInfo['id']])->whereTime('create_time', 'today')->count();
				$data['day_no'] = $dayNo+1;


				$result = OrderModel::create($data);

				//保存订单商品
				$shopListData = array();
				foreach ($cartInfo['list'] as $key => $value) {
					$shopListData[$key]['good_id'] = $value->good_id;
					$shopListData[$key]['user_id'] = USER_ID;
					$shopListData[$key]['rule_id'] = $value->rule_id;
					$shopListData[$key]['rule_name'] = $value->rule_name;
					$shopListData[$key]['num'] = $value->num;
					$shopListData[$key]['good_name'] = $value->good_name;
					$shopListData[$key]['price'] = $value->good_price;
					$shopListData[$key]['shop_name'] = $value->shop_name;
					$shopListData[$key]['cost_price'] = $value->cost_price;
					$shopListData[$key]['agent_price'] = $value->agent_price;
				}

				$result->OrderShoplist()->saveAll($shopListData);


						if($result){


							//清空购物车
							CartModel::destroy(['user_id'=>USER_ID]);

							//减库存
							foreach ($cartInfo['rule_id_arr'] as $num => $value) {
								 Goodsrule::where('id', $value)->setDec('stock', $num);
							}


							//余额支付和微信支付减余额
							if($data['pay'] == 3){
								WxUser::where('id', USER_ID)->setDec('balance', $data['total']);
							}elseif($data['pay'] == 1){
								WxUser::where('id', USER_ID)->setDec('balance', $data['balance']);
							}
							//更新优惠券状态和使用时间
							if(cookie('?couponlist_id')){
								CouponList::where('id', cookie('couponlist_id'))->update(['status' => 1, 'use_time'=>time(), 'order_id'=>$result->id]);
								cookie('couponlist_id', null);
							}

							update_session(USER_ID);


							if($data['pay'] == 2  || $data['pay'] == 3){
								sendTemplateMessage($data['title'], $cartInfo['num']);
								return $this->fetch('qiyesuccess');
							}

						}


						$openid = $userInfo['openid'];
						$body = $result['title'];
						$out_trade_no = $result['out_trade_no'];
						$total_fee = $result['pay_price']*100;
						$notify_url = 'http://www.xgw0851.com/index/pay/notify';
						$pay = & load_wechat('Pay');
						$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
						$options = $pay->createMchPay($prepayid);
						$options = json_encode($options);

						$this->assign('options', $options);
						$this->assign('info', $result);
						return $this->fetch('qiyewxpay');


		}
	}

	public function qiyepay($id = null){
		if($id){
			$userInfo = session('user');
			$result = OrderModel::get($id);
			$openid = $userInfo['openid'];
			$body = $result['title'];
			$out_trade_no = $result['out_trade_no'];
			$total_fee = $result['pay_price']*100;//$result['pay_price']*100
			$notify_url = 'http://www.xgw0851.com/index/pay/notify';
			$pay = & load_wechat('Pay');
			$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
			$options = $pay->createMchPay($prepayid);
			$options = json_encode($options);

			$this->assign('options', $options);
			$this->assign('info', $result);

			//跳转微信支付页面
			return $this->fetch('qiyewxpay');
		}
	}

	public function qiyeindex($cid = null){
		$info = parent::setQiyeCommon();
		$mapss['user_id'] = USER_ID;
		$mapss['buystatus'] = array('gt','-1');
		$mapss['company_id'] = $cid;
		$list = OrderModel::where($mapss)->order('id desc')->order('id desc')->select();
		
		//该企业所有的3天类的订单
		
	
		$weekend=date("Y-m-d H:i:s", strtotime('-3 days'));//3天之内的数据
		$mapcopy['create_time'] = array('egt', $weekend);
		$mapcopy['buystatus'] = array('gt','-1');
		$mapcopy['company_id'] = $cid;
		$listcopy = OrderModel::where($mapcopy)->order('id asc')->order('id asc')->select();
		
		
		$this->assign('list', $list);
		$this->assign('listcopy', $listcopy);
		return $this->fetch();
	}

}
